package com.iter.devbox.juc;

import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCompletionService {

	public static void completionService () throws InterruptedException, ExecutionException {
		
		ExecutorService executorService = Executors.newCachedThreadPool();
		CompletionService<String> completionService = new ExecutorCompletionService<String>(executorService);
		
		List<Future<String>> list = new ArrayList<Future<String>>();
		for (int i=0; i<5; i++) {
			final int NO = i;
			Callable<String> task = new Callable<String>() {
				public String call() throws Exception {
					return "task... " + NO;
				}   
			};   
			Future<String> future = completionService.submit(task);
			list.add(future);
		} 
		
		for (Future<String> future : list) {
			System.out.println("按线程提交顺序获取结果：" + future.get());
		}
		
		for(int i=0; i<5; i++) {
			//take方法等待下一个结果并返回 Future对象
			//poll不等待，有结果就返回一个 Future对象，没有结果就返回 null，所以会空指针异常
			Future<String> task = completionService.take();
			String ret = task.get();
			System.out.println("哪个线程先执行完就先返回哪个线程的结果：" + ret);
		}
		
		//关闭线程池   
		executorService.shutdown();
	}
	
	public static void main(String[] args) throws Throwable {
		completionService();
	}
}
